﻿using System;
using System.IO;
using System.Windows;
using MyFloridaHouse.libSvCommonUtilities;
using MyFloridaHouse.libSvOpenDistricts.Dialogs;
using MyFloridaHouse.libSvUtilities.Logging;
using MyFloridaHouse.ServiceConn.DistrBldrSvcRef;

namespace MyFloridaHouse.libSvOpenDistricts.ViewModel
{
    public partial class ViewModelBase
    {
        FileListDlg fileListDlg = null;

        private bool CmdFileImportCloudCanExecute(object parameter)
        {
            return (!isDialogOpen);
        }

        private void CmdFileImportCloudExecute(object parameter)
        {
            if (!isDialogOpen)
            {
                ReserveDialog(CmdFileImportCloud);
                if (districtPlan.districtCount > 0)
                {
                    PlanOverwriteConfirmDlg planOverwriteConfirmDlg = new PlanOverwriteConfirmDlg(OnMemberPropertyChanged, DisplayPanelForDialogs);
                    planOverwriteConfirmDlg.Start(StartFileImportCloud);
                }
                else
                {
                    StartFileImportCloud(true);
                }
            }
        }


        private void StartFileImportCloud(bool result)
        {
            if (!result)
            {
                ReleaseDialog(CmdFileImportCloud);
            }
            else
            {
                try
                {
                    //TODO:  Need to modify this to accept current or submitted plans
                    serviceDAL.GetFileInfo(Constants.CloudCurrentPlansDirectory, new System.EventHandler<GetCloudFileInfoCompletedEventArgs>(GetFileInfoCompleted));
                }
                catch (Exception ex)
                {
                    Log.HandleInternalError("Unable to get file from cloud " + ex.Message);
                    ReleaseDialog(CmdFileImportCloud);
                }
            }
        }


        private void GetFileInfoCompleted(object sender, GetCloudFileInfoCompletedEventArgs args)
        {
            // error in WCF service call
            if (Log.HandleException(args.Error))
            {
                ReleaseDialog(CmdFileImportCloud);
                return;
            }

            // unknown error in the service method
            if (args.Result == null)
            {
                Log.HandleInternalError("Error getting File Info from service " + args.Error.Message.ToString());
                ReleaseDialog(CmdFileImportCloud);
                return;
            }
            else
            {
                // caught error in the service method
                if (Log.HandleServerError("GetFileInfoCompleted", args.Result.errorMessage))
                {
                    ReleaseDialog(CmdFileImportCloud);
                    return;
                }

                // Everything OK!


                fileListDlg = new FileListDlg(OnMemberPropertyChanged, DisplayPanelForDialogs);
                fileListDlg.fileNameList = args.Result.files;
                fileListDlg.Start(OnCloudFileSelected); 
            }
        }

        private void OnCloudFileSelected(bool result)
        {
            if (!result)
            {
                ReleaseDialog(CmdFileImportCloud);
                return;
            }
            else
            {
                try
                {
                    if (fileListDlg.selectedFileInfo == null)
                    {
                        // no file selected
                        ReleaseDialog(CmdFileImportCloud);
                    }
                    else
                    {
                        serviceDAL.GetFile(fileListDlg.selectedFileInfo, new System.EventHandler<GetCloudFileCompletedEventArgs>(GetCloudFileCompleted));
                    }
                }
                catch (Exception ex)
                {
                    Log.HandleInternalError("Error getting file from cloud : " + ex.Message);
                    ReleaseDialog(CmdFileImportCloud);
                }
            }
        }


        public void GetCloudFileCompleted(object sender, GetCloudFileCompletedEventArgs args)
        {
            try
            {
                fileListDlg = null;

                // error in WCF service call
                if (Log.HandleException(args.Error))
                {
                    ReleaseDialog(CmdFileImportCloud);
                    return;
                }

                // unknown error in the service method
                if (args.Result == null)
                {
                    Log.HandleServerError("GetCloudFileCompleted", "Unknown Error getting File from Service ");
                    ReleaseDialog(CmdFileImportCloud);
                }
                else
                {
                    // caught error in the service method
                    if (Log.HandleServerError("GetCloudFileCompleted", args.Result.errorMessage))
                    {
                        ReleaseDialog(CmdFileImportCloud);
                        return;
                    }

                    // Everything OK!
                    if (args == null)
                    {
                        Log.HandleInternalError("GetCloudFileCompleted: Unable to load file, invalid file name selected");
                        ReleaseDialog(CmdFileImportCloud);
                        return;
                    }

                    try
                    {
                        MemoryStream fileDataStream;
                        //TODO: Instead of using format = KMZ from fileinfo to indicate file shouldn't be decompressed, should use new boolean table field called "isCompressed"
                        if (args.Result.fileInfo.isCompressed)
                        {
                            fileDataStream = new MemoryStream(CompressionManager.DecompressToByteArray(args.Result.fileData));
                        }
                        else
                        {
                            // kmz is already compressed
                            fileDataStream = new MemoryStream(args.Result.fileData);
                        }
                        string[] fileNamePiecesArray = args.Result.fileInfo.fileName.Split('.');
                        if (fileNamePiecesArray.Length > 1)
                        {
                            DistrictPlanLoadFile(fileDataStream, args.Result.fileInfo.fileName, fileNamePiecesArray[1]);
                        }

                    }
                    catch (Exception ex)
                    {
                        Log.HandleInternalError("GetCloudFileCompleted: Error opening cloud file, " + ex.Message.ToString());
                    }
                    finally
                    {
                        // TODO: Indicate file load is going on
                        //isFileLoading = false;
                        ReleaseDialog(CmdFileImportCloud);

                    }

                }
            }
            catch { }
            finally
            {
                ReleaseDialog(CmdFileImportCloud);
            }

        }

    }
}
